"""
Author: 2023-07-25 19:32:24
LastEditors: 2023-07-25 19:32:24
LastEditTime: 2023-07-25 19:32:24
"""

import traceback
from hashlib import md5

# 添加导入语句
# 在 SQLAlchemy 2.0 及之后的版本中，`declarative_base` 从 `sqlalchemy.orm` 导入
from sqlalchemy import create_engine
from sqlalchemy.orm import declarative_base, sessionmaker

from db.crud import check_user_exists, create_user

######数据库相关配置#####
Base = declarative_base()
SQLALCHEMY_DB_URI = "sqlite:///./db2.db"
engine = create_engine(SQLALCHEMY_DB_URI, connect_args={"check_same_thread": False})


db_session = sessionmaker(engine)
# Base.metadata.create_all(engine)


# Dependency
def get_db():
    db = db_session()
    try:
        yield db
    finally:
        db.close()


########################
def init_db() -> None:
    Base.metadata.create_all(engine)
    db = db_session()
    if not check_user_exists(db, "admin"):
        create_user(db=db, uname="admin", pwd=md5(b"123456").hexdigest(), role=0)


async def close_db() -> None:
    try:
        db_session.close_all()
    except:
        traceback.print_exc()
